package com.wocai.jrt.admin.common.service.impl;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.vteba.security.publisher.filter.PublisherUserAuthenticationToken;
import com.vteba.security.publisher.security.PublisherDetailsService;
import com.vteba.security.publisher.security.user.PUserDetails;
import com.vteba.security.spi.cache.SecurityPublisherUserCache;
import com.wocai.jrt.orgadmin.issuers.model.Issuers;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersService;
@Named
public class SaasPublisherDetailsServiceImpl implements PublisherDetailsService {
	private static final Logger LOGGER = LoggerFactory.getLogger(SaasPublisherDetailsServiceImpl.class);
	
	@Inject
	private IssuersService issuersServiceImpl;
	
	@Inject
	private SecurityPublisherUserCache redisSpringSecurityPublisherUserCache;

	@Override
	@Deprecated
	public UserDetails loadUserByUsername(String s)
			throws UsernameNotFoundException {
		LOGGER.warn("this method is deprecated.");
		return null;
	}

	@Override
	public PUserDetails loadUser(String account,
			PublisherUserAuthenticationToken token) {
		String tenantCode = token.getOrgCode();
		Issuers iss = new Issuers();
		
		iss.setAccount(account);
		iss.setOrgCode(tenantCode);
		iss.setDisable(false);
		iss = issuersServiceImpl.unique(iss);
		
		if (iss != null) {
			checkCase(iss, account, token.getOrgCode());
			redisSpringSecurityPublisherUserCache.putUserInCache(iss);
		} else {
			LOGGER.error("cannot find User from Database, userName=[{}]", account);
			throw new UsernameNotFoundException("userName=[" + account + "], user cannot exist.");
		}
		return iss;
	}

	@Override
	public List<GrantedAuthority> buildGranted(PUserDetails user) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 检查区分大小写，因为mysql对varchar类型，默认不区分大小写<br>
	 * 改成二进制可以，但是没有确认过是否对index等有影响，这里<br>
	 * 暂时先这么判断。
	 * @param user 从数据库中查询到的用户信息
	 * @param userName 前端传来的数据，账号
	 * @param tenantId 租户代码（orgCode暂未使用）
	 */
	private void checkCase(PUserDetails user, String userName, String tenantId) {
		if (!userName.equals(user.getAccount())) {
			throw new UsernameNotFoundException("userName=[" + userName + "], user account case not matche.");
		}
	}

}
